<?php


namespace App\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

/**
 * 充值服务
 * Class RechargeService
 * @package App\Services
 */
class RechargeService extends BasePayService
{
    private $uid;
    private $money;
    private $pay_type;

    /**
     * 支付
     * @param int $uid
     * @param int $money
     * @param $pay_type
     * @return mixed
     */
    public static function startPay(int $uid,int $money, $pay_type)
    {
        if ($money < 10) {
            throw new \Exception('充值金额最低为10元');
        }
        return (new self($uid, $money, $pay_type))->pay();
    }

    /**
     * 回调
     * @param array $notifyInfo
     * @throws \Exception
     */
    public static function notify(array $notifyInfo)
    {
        $orderInfo = DB::table('user_recharge_order')->where('order_no', $notifyInfo['ordernumber'])
            ->where('pay_status', 2)
            ->first();
        if (!$orderInfo) {
            throw new \Exception('未查询到待支付订单');
        }
        $that = new self($orderInfo->user_id, $orderInfo->money, $orderInfo->pay_type);
        $that->orderInfo = $orderInfo;

        $userInfo = DB::table('users')->find($that->orderInfo->user_id);
        if (!$userInfo) {
            throw new \Exception('用户信息错误');
        }
        // 更新订单信息
        $update = [
            'resp_params' => json_encode($notifyInfo),
            'pay_status' => $notifyInfo['status'] == 1 ? 1 : 3,
            'plat_order_no' => $notifyInfo['tradeno']
        ];
        Db::beginTransaction();
        try {
            if (!DB::table('user_recharge_order')->where('id', $orderInfo->id)->update($update)) {
                throw new \Exception('更新订单失败');
            }
            // 增加用户乐游币
            MemberService::setMemberBalance(
                $userInfo,
                MemberService::BalanceTypeLy,
                MemberService::FromTypeRecharge,
                $that->orderInfo->id,
                ($that->orderInfo->money*100) + $that->orderInfo->gift_money,
                '充值订单'
            );
            // 发放订单各种赠送
            // 玩服积分
            if ($that->orderInfo->gift_wf) {
                MemberService::setMemberBalance(
                    $userInfo,
                    MemberService::BalanceTypeWf,
                    MemberService::FromTypeRecharge,
                    $that->orderInfo->id,
                    $that->orderInfo->gift_wf,
                    '充值订单赠送'
                );
            }
            // 返利积分
            if ($that->orderInfo->gift_integral) {
                MemberService::setMemberBalance(
                    $userInfo,
                    MemberService::BalanceTypeJf,
                    MemberService::FromTypeRecharge,
                    $that->orderInfo->id,
                    $that->orderInfo->gift_integral,
                    '充值赠送商城积分'
                );
            }
            // 上级奖励
            /*if ($userInfo->from_id) {
                $that->sendParentReward($that->orderInfo->id, $userInfo, $userInfo->from_id, $that->orderInfo->money);
            }*/
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * RechargeService constructor.
     * @param int $uid
     * @param int $money
     * @param string $pay_type
     * @throws \Exception
     */
    public function __construct(int $uid = 0,int $money = 0,string $pay_type = 'WEIXIN')
    {
        parent::__construct();
        $this->uid = $uid;
        $this->money = $money;
        $this->pay_type = $pay_type;
    }

    /**
     * 发起支付
     * @return array
     * @throws AppRuntimeException
     */
    private function pay()
    {
        // 计算抵扣金额
        $data = [
            'gameuser'=>'wanfu591',
            'paytype'=>$this->pay_type,
            'money'=>$this->money,
            'ordernumber'=>$this->getOrderNo($this->uid, 1),
            'remark' => 1,
        ];
        $this->createOrder($data);
        $payInfo = $this->request('', $data);
        if ($payInfo['resultcode'] != 200) {
            throw new \Exception($payInfo['resultmsg']);
        }
        // 如果type为1，则处理成2
        if ($payInfo['resultdata']['type'] == 1) {
            // 将内容写入缓存
            Cache::put(self::getPayPageCacheKey($this->orderId, 1), $payInfo['resultdata']['data'], 3600);
            $payInfo['resultdata']['type'] = 2;
            $payInfo['resultdata']['data'] = '/api/pay/payPage/1/'.$this->orderId;
        }
        return ['order_id' => $this->orderId, 'pay_info' => $payInfo];
    }


    /**
     * 创建订单
     * @param $req
     * @throws AppRuntimeException
     */
    private function createOrder($req)
    {
        $userInfo = DB::table('users')->find($this->uid);
        $giftInfo = self::getGiftIntegral($this->uid, $this->money);
        $order = [
            'pay_plat_id' => $this->payPlat->id,
            'user_id' => $this->uid,
            'union_id' => $userInfo->wx_unionid,
            'unionid' => $userInfo->unionid,
            'money' => $this->money,
            'gift_money' => $giftInfo['gift_ly'],
            'gift_integral' => $giftInfo['integral'],
            'gift_wf' => $giftInfo['gift_wf'] + $giftInfo['level_wf'],
            'req_params' => json_encode($req),
            'pay_type' => $this->pay_type,
            'order_no' => $req['ordernumber'],
            'plat_order_no' => '',
            'contact' => '',
            'pay_status' => 2,
            'game_user' => '',
            'create_time' => time(),
            'update_time' => time(),
            'site_host' => $_SERVER['HTTP_HOST'] ?? ''
        ];
        $this->orderId = DB::table('user_recharge_order')->insertGetId($order);
        if (!$this->orderId) {
            throw new \Exception('生成订单失败');
        }
    }

    // 发放上级奖励
    private function sendParentReward($orderId, $curUser, $uid, $money)
    {
        $parent = DB::table('users')->find($uid);
        if (!$parent) {
            return;
        }
        $hasOrder = DB::table('user_recharge_order')
            ->where('user_id', $curUser->id)
            ->where('pay_status', 1)
            ->count();
        $isNew = !$hasOrder && (time() - strtotime($curUser->created_at) < (86400*3));
        if ($isNew) {
            $rate = DB::table('sys_config')->where('key', 'yx_new_rate')->value('value');
        } else {
            $rate = DB::table('sys_config')->where('key', 'yx_old_rate')->value('value');
        }
        $reward = ceil($money*($rate/100)) * 100;
        MemberService::setMemberBalance(
            $parent,
            MemberService::BalanceTypeLy,
            MemberService::FromTypeReward,
            $orderId,
            $reward,
            '好友充值奖励'
        );
    }


    public static function getGiftIntegral($uid, $money)
    {
        $resp = [
            'integral' => 0, // 积分
            'level_wf' => 0, // 等级玩服积分
            'gift_ly' => 0, // 充值规则奖励乐游币
            'gift_wf' => 0, // 充值规则奖玩服积分
        ];
        if (!$uid) {
            return $resp;
        }
        $user = DB::table('users')->find($uid);
        if (!$user || !$user->level_id) {
            return $resp;
        }
        $userLevel = DB::table('user_level')->find($user->level_id);
        if (!$userLevel) {
            return $resp;
        }
        if ($userLevel->ly_rate) {
            $resp['level_wf'] = floor($money*($userLevel->ly_rate/100)) * 100;
            if ($money < $userLevel->min_money) {
                $resp['level_wf'] = 0;
            }
        }
        if ($userLevel->integral_rate) {
            $resp['integral'] = floor($money*($userLevel->integral_rate/100));
        }
        // 是否有充值规则中的奖励金额
        $rule = DB::table('recharge_rule')->where('need_money', $money)->first();
        if ($rule) {
            $resp['gift_ly'] = floor($rule->gift_ly);
            $resp['gift_wf'] = floor($rule->gift_wf);
        }
        return $resp;
    }
}
